import React, { PureComponent } from 'react'

export class App extends PureComponent {
  constructor() {
    super()

    this.state = {
      books: [
        {name: "《哈利·波特与魔法石》", price: 29.99, count: 0},
        {name: "《鲁滨逊漂流记》", price: 19.99, count: 0},
        {name: "《百年孤独》", price: 39.99, count: 0},
        {name: "《1984》", price: 24.99, count: 0},
        {name: "《红楼梦》", price: 34.99, count: 0}
      ]
    }
  }

  addBook() {
    const book = { name: "《JavaScript程序设计》", price: 40.99, count: 0 }
    // 1. 直接修改state中的数据，在PureComponent中无法生效
    // this.state.books.push(book)
    // this.setState({
    //   books: this.state.books
    // })
    // 2. 先对数据进行浅拷贝,对新的数据进行修改赋值给旧的数据
    const books = [...this.state.books]
    books.push(book)
    this.setState({
      books: books
    })
  }

  addCount(index) {
    console.log(index);
    const books = [...this.state.books]
    books[index].count++
    this.setState({
      books: books
    })
  }

  render() {
    const { books } = this.state
    return (
      <div>
        <ul>
          {
            books.map((item, index) => {
              return (
                <li key={item.name}>
                  {item.name} - {item.price} - 数量：{item.count}
                  <button onClick={() => this.addCount(index)}>+1</button>
                </li>
              )
            })
          }
        </ul>
        <button onClick={() => this.addBook()}>添加新书籍</button>
      </div>
    )
  }
}

export default App